// utils/maintenanceManager.js
// 数据清理和维护管理器

import { TaskStorage } from './storage.js'
import { ErrorHandler, FeedbackManager, StorageErrorHandler, ERROR_TYPES, ERROR_LEVELS } from './errorHandler.js'

/**
 * 数据维护管理器
 */
class MaintenanceManager {
  /**
   * 数据清理选项
   */
  static CLEANUP_OPTIONS = {
    COMPLETED_TASKS: 'completedTasks',
    OLD_TASKS: 'oldTasks',
    ERROR_LOGS: 'errorLogs',
    CACHE_DATA: 'cacheData',
    BACKUP_DATA: 'backupData',
    ALL_DATA: 'allData'
  }

  /**
   * 获取存储空间使用情况
   */
  static async getStorageUsage() {
    try {
      const storageInfo = await new Promise((resolve, reject) => {
        wx.getStorageInfo({
          success: resolve,
          fail: reject
        })
      })
      
      const usage = {
        currentSize: storageInfo.currentSize,
        limitSize: storageInfo.limitSize,
        usagePercentage: Math.round((storageInfo.currentSize / storageInfo.limitSize) * 100),
        keys: storageInfo.keys,
        freeSize: storageInfo.limitSize - storageInfo.currentSize
      }
      
      // 分析各个存储项的大小
      const keyDetails = await this.analyzeStorageKeys(storageInfo.keys)
      
      return {
        success: true,
        data: {
          ...usage,
          keyDetails
        }
      }
    } catch (error) {
      console.error('获取存储使用情况失败:', error)
      StorageErrorHandler.handleStorageError(error, 'check')
      return {
        success: false,
        message: '获取存储使用情况失败'
      }
    }
  }

  /**
   * 分析存储键的详细信息
   */
  static async analyzeStorageKeys(keys) {
    const keyDetails = []
    
    for (const key of keys) {
      try {
        const data = wx.getStorageSync(key)
        const size = JSON.stringify(data).length
        
        keyDetails.push({
          key,
          size,
          type: this.getDataType(key),
          lastModified: this.getLastModified(key, data)
        })
      } catch (error) {
        console.error(`分析存储键 ${key} 失败:`, error)
        keyDetails.push({
          key,
          size: 0,
          type: 'unknown',
          lastModified: null,
          error: true
        })
      }
    }
    
    return keyDetails.sort((a, b) => b.size - a.size)
  }

  /**
   * 获取数据类型
   */
  static getDataType(key) {
    if (key.includes('tasks')) return 'tasks'
    if (key.includes('settings')) return 'settings'
    if (key.includes('backup')) return 'backup'
    if (key.includes('error')) return 'error'
    if (key.includes('cache')) return 'cache'
    return 'other'
  }

  /**
   * 获取最后修改时间
   */
  static getLastModified(key, data) {
    try {
      if (Array.isArray(data)) {
        // 任务数组，找最新的更新时间
        const latestTime = data.reduce((latest, item) => {
          const time = item.updateTime || item.createTime || item.timestamp
          return time > latest ? time : latest
        }, 0)
        return latestTime || null
      }
      
      if (typeof data === 'object' && data.timestamp) {
        return data.timestamp
      }
      
      return null
    } catch (error) {
      return null
    }
  }

  /**
   * 清理已完成的任务
   */
  static async cleanupCompletedTasks(options = {}) {
    const {
      olderThanDays = 30,
      keepCount = 10,
      confirmCleanup = true
    } = options
    
    try {
      const tasks = TaskStorage.getAllTasks()
      const completedTasks = tasks.filter(task => task.status === 1)
      
      if (completedTasks.length === 0) {
        return {
          success: true,
          message: '没有已完成的任务需要清理',
          cleaned: 0
        }
      }
      
      const cutoffTime = Date.now() - (olderThanDays * 24 * 60 * 60 * 1000)
      const tasksToClean = completedTasks
        .filter(task => task.completeTime < cutoffTime)
        .sort((a, b) => b.completeTime - a.completeTime)
        .slice(keepCount) // 保留最新的keepCount个
      
      if (tasksToClean.length === 0) {
        return {
          success: true,
          message: '没有符合清理条件的已完成任务',
          cleaned: 0
        }
      }
      
      if (confirmCleanup) {
        const confirmed = await FeedbackManager.showConfirm({
          title: '清理已完成任务',
          content: `将清理 ${tasksToClean.length} 个超过 ${olderThanDays} 天的已完成任务，保留最新的 ${keepCount} 个`,
          confirmText: '确定清理',
          confirmColor: '#ff4757'
        })
        
        if (!confirmed) {
          return {
            success: false,
            message: '用户取消清理操作',
            cleaned: 0
          }
        }
      }
      
      // 执行清理
      let cleanedCount = 0
      for (const task of tasksToClean) {
        const success = TaskStorage.deleteTask(task.id, true) // 永久删除
        if (success) {
          cleanedCount++
        }
      }
      
      return {
        success: true,
        message: `成功清理 ${cleanedCount} 个已完成任务`,
        cleaned: cleanedCount
      }
    } catch (error) {
      console.error('清理已完成任务失败:', error)
      ErrorHandler.handleError(error, ERROR_TYPES.SYSTEM, ERROR_LEVELS.ERROR, {
        operation: 'cleanupCompletedTasks',
        options
      })
      return {
        success: false,
        message: '清理已完成任务失败'
      }
    }
  }

  /**
   * 清理旧任务数据
   */
  static async cleanupOldTasks(options = {}) {
    const {
      olderThanDays = 90,
      includeDeleted = true,
      confirmCleanup = true
    } = options
    
    try {
      const allTasks = TaskStorage.getAllTasks(includeDeleted)
      const cutoffTime = Date.now() - (olderThanDays * 24 * 60 * 60 * 1000)
      
      const tasksToClean = allTasks.filter(task => {
        const taskTime = task.updateTime || task.createTime
        return taskTime < cutoffTime && (includeDeleted || task.isDeleted)
      })
      
      if (tasksToClean.length === 0) {
        return {
          success: true,
          message: '没有需要清理的旧任务',
          cleaned: 0
        }
      }
      
      if (confirmCleanup) {
        const confirmed = await FeedbackManager.showConfirm({
          title: '清理旧任务',
          content: `将永久删除 ${tasksToClean.length} 个超过 ${olderThanDays} 天的旧任务`,
          confirmText: '确定清理',
          confirmColor: '#ff4757'
        })
        
        if (!confirmed) {
          return {
            success: false,
            message: '用户取消清理操作',
            cleaned: 0
          }
        }
      }
      
      // 执行清理
      let cleanedCount = 0
      for (const task of tasksToClean) {
        const success = TaskStorage.deleteTask(task.id, true) // 永久删除
        if (success) {
          cleanedCount++
        }
      }
      
      return {
        success: true,
        message: `成功清理 ${cleanedCount} 个旧任务`,
        cleaned: cleanedCount
      }
    } catch (error) {
      console.error('清理旧任务失败:', error)
      ErrorHandler.handleError(error, ERROR_TYPES.SYSTEM, ERROR_LEVELS.ERROR, {
        operation: 'cleanupOldTasks',
        options
      })
      return {
        success: false,
        message: '清理旧任务失败'
      }
    }
  }

  /**
   * 清理错误日志
   */
  static async cleanupErrorLogs(options = {}) {
    const {
      keepCount = 20,
      confirmCleanup = true
    } = options
    
    try {
      const logs = ErrorHandler.getErrorLogs()
      
      if (logs.length <= keepCount) {
        return {
          success: true,
          message: '错误日志数量在合理范围内',
          cleaned: 0
        }
      }
      
      const cleanCount = logs.length - keepCount
      
      if (confirmCleanup) {
        const confirmed = await FeedbackManager.showConfirm({
          title: '清理错误日志',
          content: `将清理 ${cleanCount} 条旧的错误日志，保留最新的 ${keepCount} 条`,
          confirmText: '确定清理',
          confirmColor: '#ff4757'
        })
        
        if (!confirmed) {
          return {
            success: false,
            message: '用户取消清理操作',
            cleaned: 0
          }
        }
      }
      
      // 保留最新的日志
      const sortedLogs = logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
      const logsToKeep = sortedLogs.slice(0, keepCount)
      
      wx.setStorageSync('error_logs', logsToKeep)
      
      return {
        success: true,
        message: `成功清理 ${cleanCount} 条错误日志`,
        cleaned: cleanCount
      }
    } catch (error) {
      console.error('清理错误日志失败:', error)
      ErrorHandler.handleError(error, ERROR_TYPES.SYSTEM, ERROR_LEVELS.ERROR, {
        operation: 'cleanupErrorLogs',
        options
      })
      return {
        success: false,
        message: '清理错误日志失败'
      }
    }
  }

  /**
   * 清理缓存数据
   */
  static async cleanupCacheData(options = {}) {
    const { confirmCleanup = true } = options
    
    try {
      const cacheKeys = [
        'cache_',
        'temp_',
        'preview_',
        'thumbnail_'
      ]
      
      const allKeys = wx.getStorageInfoSync().keys
      const cacheKeysToDelete = allKeys.filter(key => 
        cacheKeys.some(prefix => key.startsWith(prefix))
      )
      
      if (cacheKeysToDelete.length === 0) {
        return {
          success: true,
          message: '没有缓存数据需要清理',
          cleaned: 0
        }
      }
      
      if (confirmCleanup) {
        const confirmed = await FeedbackManager.showConfirm({
          title: '清理缓存',
          content: `将清理 ${cacheKeysToDelete.length} 个缓存项`,
          confirmText: '确定清理',
          confirmColor: '#ff4757'
        })
        
        if (!confirmed) {
          return {
            success: false,
            message: '用户取消清理操作',
            cleaned: 0
          }
        }
      }
      
      // 执行清理
      let cleanedCount = 0
      for (const key of cacheKeysToDelete) {
        try {
          wx.removeStorageSync(key)
          cleanedCount++
        } catch (error) {
          console.error(`清理缓存项 ${key} 失败:`, error)
        }
      }
      
      return {
        success: true,
        message: `成功清理 ${cleanedCount} 个缓存项`,
        cleaned: cleanedCount
      }
    } catch (error) {
      console.error('清理缓存数据失败:', error)
      ErrorHandler.handleError(error, ERROR_TYPES.SYSTEM, ERROR_LEVELS.ERROR, {
        operation: 'cleanupCacheData',
        options
      })
      return {
        success: false,
        message: '清理缓存数据失败'
      }
    }
  }

  /**
   * 数据修复
   */
  static async repairData() {
    try {
      const repairResults = []
      
      // 修复任务数据
      const taskRepairResult = await this.repairTaskData()
      repairResults.push(taskRepairResult)
      
      // 修复设置数据
      const settingsRepairResult = await this.repairSettingsData()
      repairResults.push(settingsRepairResult)
      
      const totalRepaired = repairResults.reduce((sum, result) => sum + result.repaired, 0)
      
      return {
        success: true,
        message: `数据修复完成，共修复 ${totalRepaired} 项`,
        results: repairResults
      }
    } catch (error) {
      console.error('数据修复失败:', error)
      ErrorHandler.handleError(error, ERROR_TYPES.SYSTEM, ERROR_LEVELS.ERROR, {
        operation: 'repairData'
      })
      return {
        success: false,
        message: '数据修复失败'
      }
    }
  }

  /**
   * 修复任务数据
   */
  static async repairTaskData() {
    try {
      const tasks = TaskStorage.getAllTasks(true)
      let repairedCount = 0
      
      for (const task of tasks) {
        let needsRepair = false
        const repairedTask = { ...task }
        
        // 修复缺失的字段
        if (!repairedTask.id) {
          repairedTask.id = Date.now().toString() + Math.random().toString(36).substr(2, 9)
          needsRepair = true
        }
        
        if (!repairedTask.createTime) {
          repairedTask.createTime = Date.now()
          needsRepair = true
        }
        
        if (!repairedTask.updateTime) {
          repairedTask.updateTime = repairedTask.createTime
          needsRepair = true
        }
        
        if (typeof repairedTask.status !== 'number') {
          repairedTask.status = 0
          needsRepair = true
        }
        
        if (typeof repairedTask.priority !== 'number') {
          repairedTask.priority = 2
          needsRepair = true
        }
        
        if (typeof repairedTask.isDeleted !== 'boolean') {
          repairedTask.isDeleted = false
          needsRepair = true
        }
        
        if (needsRepair) {
          TaskStorage.updateTask(repairedTask.id, repairedTask)
          repairedCount++
        }
      }
      
      return {
        type: 'tasks',
        message: `修复了 ${repairedCount} 个任务数据`,
        repaired: repairedCount
      }
    } catch (error) {
      console.error('修复任务数据失败:', error)
      return {
        type: 'tasks',
        message: '修复任务数据失败',
        repaired: 0
      }
    }
  }

  /**
   * 修复设置数据
   */
  static async repairSettingsData() {
    try {
      const settings = wx.getStorageSync('todolist_settings') || {}
      const defaultSettings = {
        theme: 'default',
        notifications: true,
        autoBackup: false,
        language: 'zh-CN'
      }
      
      let needsRepair = false
      const repairedSettings = { ...settings }
      
      // 添加缺失的设置项
      for (const [key, value] of Object.entries(defaultSettings)) {
        if (!(key in repairedSettings)) {
          repairedSettings[key] = value
          needsRepair = true
        }
      }
      
      if (needsRepair) {
        wx.setStorageSync('todolist_settings', repairedSettings)
        return {
          type: 'settings',
          message: '修复了设置数据',
          repaired: 1
        }
      }
      
      return {
        type: 'settings',
        message: '设置数据正常',
        repaired: 0
      }
    } catch (error) {
      console.error('修复设置数据失败:', error)
      return {
        type: 'settings',
        message: '修复设置数据失败',
        repaired: 0
      }
    }
  }

  /**
   * 数据健康检查
   */
  static async healthCheck() {
    try {
      const results = {
        storage: await this.checkStorageHealth(),
        tasks: await this.checkTasksHealth(),
        settings: await this.checkSettingsHealth(),
        performance: await this.checkPerformanceHealth()
      }
      
      const issues = []
      let totalScore = 0
      let maxScore = 0
      
      for (const [category, result] of Object.entries(results)) {
        totalScore += result.score
        maxScore += result.maxScore
        if (result.issues.length > 0) {
          issues.push(...result.issues.map(issue => ({ category, ...issue })))
        }
      }
      
      const healthScore = Math.round((totalScore / maxScore) * 100)
      
      return {
        success: true,
        healthScore,
        results,
        issues,
        recommendations: this.generateRecommendations(issues, healthScore)
      }
    } catch (error) {
      console.error('健康检查失败:', error)
      return {
        success: false,
        message: '健康检查失败'
      }
    }
  }

  /**
   * 检查存储健康状况
   */
  static async checkStorageHealth() {
    const usage = await this.getStorageUsage()
    const issues = []
    let score = 100
    
    if (usage.success) {
      const { usagePercentage } = usage.data
      
      if (usagePercentage > 90) {
        issues.push({
          level: 'error',
          message: '存储空间严重不足',
          suggestion: '建议立即清理数据'
        })
        score -= 50
      } else if (usagePercentage > 70) {
        issues.push({
          level: 'warning',
          message: '存储空间使用率较高',
          suggestion: '建议清理部分数据'
        })
        score -= 20
      }
    } else {
      issues.push({
        level: 'error',
        message: '无法获取存储信息',
        suggestion: '检查存储权限'
      })
      score -= 30
    }
    
    return {
      score,
      maxScore: 100,
      issues
    }
  }

  /**
   * 检查任务数据健康状况
   */
  static async checkTasksHealth() {
    const tasks = TaskStorage.getAllTasks(true)
    const issues = []
    let score = 100
    
    // 检查数据完整性
    const invalidTasks = tasks.filter(task => 
      !task.id || !task.title || typeof task.status !== 'number'
    )
    
    if (invalidTasks.length > 0) {
      issues.push({
        level: 'warning',
        message: `发现 ${invalidTasks.length} 个数据不完整的任务`,
        suggestion: '运行数据修复功能'
      })
      score -= 20
    }
    
    // 检查任务数量
    const activeTasks = tasks.filter(task => !task.isDeleted)
    if (activeTasks.length > 1000) {
      issues.push({
        level: 'warning',
        message: '任务数量过多',
        suggestion: '考虑清理部分已完成任务'
      })
      score -= 10
    }
    
    return {
      score,
      maxScore: 100,
      issues
    }
  }

  /**
   * 检查设置健康状况
   */
  static async checkSettingsHealth() {
    const settings = wx.getStorageSync('todolist_settings') || {}
    const issues = []
    let score = 100
    
    const requiredSettings = ['theme', 'notifications', 'autoBackup', 'language']
    const missingSettings = requiredSettings.filter(key => !(key in settings))
    
    if (missingSettings.length > 0) {
      issues.push({
        level: 'info',
        message: `缺少 ${missingSettings.length} 个设置项`,
        suggestion: '运行数据修复功能'
      })
      score -= 5 * missingSettings.length
    }
    
    return {
      score,
      maxScore: 100,
      issues
    }
  }

  /**
   * 检查性能健康状况
   */
  static async checkPerformanceHealth() {
    const issues = []
    let score = 100
    
    // 检查错误日志数量
    const errorLogs = ErrorHandler.getErrorLogs()
    if (errorLogs.length > 50) {
      issues.push({
        level: 'warning',
        message: '错误日志过多',
        suggestion: '清理旧的错误日志'
      })
      score -= 15
    }
    
    // 检查最近错误频率
    const recentErrors = errorLogs.filter(log => {
      const logTime = new Date(log.timestamp).getTime()
      const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000
      return logTime > oneDayAgo
    })
    
    if (recentErrors.length > 10) {
      issues.push({
        level: 'error',
        message: '最近24小时错误频率过高',
        suggestion: '检查应用稳定性'
      })
      score -= 30
    }
    
    return {
      score,
      maxScore: 100,
      issues
    }
  }

  /**
   * 生成建议
   */
  static generateRecommendations(issues, healthScore) {
    const recommendations = []
    
    if (healthScore < 60) {
      recommendations.push('应用健康状况较差，建议立即进行维护')
    } else if (healthScore < 80) {
      recommendations.push('应用健康状况一般，建议定期维护')
    } else {
      recommendations.push('应用健康状况良好')
    }
    
    const errorIssues = issues.filter(issue => issue.level === 'error')
    if (errorIssues.length > 0) {
      recommendations.push('存在严重问题，请优先处理')
    }
    
    const storageIssues = issues.filter(issue => issue.category === 'storage')
    if (storageIssues.length > 0) {
      recommendations.push('建议清理存储空间')
    }
    
    return recommendations
  }
}

export { MaintenanceManager } 